﻿using System;
using System.Collections.Generic;
using System.Management;
using System.IO.Ports;

namespace LetiLib.Device
{
    public sealed class SMSSender
    {
        private static volatile SMSSender instance;
        private static object syncRoot = new Object();

        public bool isOpenned { get { return sp.IsOpen; } }

        private SMSSender() { }
        /*
        public override void Dispose()
        {
            
            if (true && (sp.Container != null))
            {
                sp.Container.Dispose();
            }
            try
            {
                if (sp.BaseStream.CanRead)
                {
                    sp.BaseStream.Close();
                    GC.ReRegisterForFinalize(sp.BaseStream);
                }
            }
            catch
            {
                // ignore exception - bug with USB - serial adapters.
            }
        }
        */
        public static SMSSender Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (syncRoot)
                    {
                        if (instance == null)
                            instance = new SMSSender();
                    }
                }

                return instance;
            }
        }

        private void sp_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            string text = sp.ReadExisting();
            if (text.Contains("RSSI") || text.Contains("BOOT"))
                return;
            if (receiveFlag == WMA_FLAG_OVER140BYTESMES)
            {
                if (text.Contains("+CMGS:"))
                {
                    if (text.Contains("OK"))
                    {
                        System.Threading.Thread.Sleep(100);
                        SendSecondMessage();
                        receiveFlag = WMA_FLAG_NORMALSTATE;
                        Disconnect();
                        return;
                    }

                }
            }
        }

        public bool Connect()
        {
            string UIPort = "";
            foreach (COMPortInfo comPort in COMPortInfo.GetCOMPortsInfo())
            {
                if (comPort.Description.Contains("PC UI Interface"))
                {
                    UIPort = comPort.Name;
                }
            }
            if (UIPort == "")
                return false;
            if (fInstaniate == 0)
            {
                sp = new SerialPort();
                sp.PortName = UIPort;
                sp.BaudRate = 9600;
                sp.StopBits = StopBits.One;
                sp.WriteBufferSize = 8000;
                sp.WriteTimeout = 10000;
                sp.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(sp_DataReceived);

                fInstaniate = 1;
            }

            try
            {
                if (!fOpen)
                {
                    sp.Open();
                    fOpen = true;
                }
                //MessageBox.Show("Connected!");
                // TODO post connected event

            }
            catch (System.Exception ex)
            {
                //MessageBox.Show(ex.Message, "Connect Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
                // TODO: post error event
                return false;

            }
            return true;
        }

        private static SerialPort sp;
        private static string phone = "";
        private static string phoneLen = "";
        private static string sms = "";
        private static int receiveFlag = WMA_FLAG_NORMALSTATE;
        private static int fInstaniate = 0;
        private static bool fOpen = false;

        const int WMA_FLAG_NORMALSTATE = 0;
        //GSM Flags
        const int WMA_FLAG_OVER140BYTESMES = 50;

        public bool Disconnect()
        {
            try
            {
                sp.Close();
            }
            catch (System.Exception ex)
            {
                //MessageBox.Show(ex.Message);
                return false;
            }
            return true;
        }
        public string sendMessage(string phoneNumber, string message, int mode)
        {
            string pn = "";
            string command = "AT+CMGS=";
            string data = "001100";
            string len = "";
            int index = 0;

            if (!sp.IsOpen)
            {
                Connect();
            }

            if (phoneNumber.Length == 12)
            {
                len = "0C";
                pn = phoneNumber;
            }
            else if (phoneNumber.Length == 11)
            {
                if (phoneNumber.Substring(0, 2) == "84")
                {
                    pn = phoneNumber + "F";
                    len = "0B";
                }
                else if (phoneNumber[0] == '0')
                {
                    len = "0C";
                    pn = "84" + phoneNumber.Substring(1);
                }
            }
            else if (phoneNumber.Length == 10)
            {
                if (phoneNumber[0] == '0')
                {
                    pn = "84" + phoneNumber.Substring(1) + "F";
                    len = "0B";
                }
                else
                {
                    pn = "84" + phoneNumber;
                    len = "0C";
                }
            }
            else
                return "Phone number format error!";

            //PDU mode
            if (mode == 0)
            {
                sp.Write("ATE0\r\n");
                sp.Write("AT+CMGF=0\r\n");
                char[] arr = pn.ToCharArray();
                for (int i = 0; i < pn.Length; i += 2)
                {
                    arr[i] = pn[i + 1];
                    arr[i + 1] = pn[i];
                }

                pn = new string(arr);
                phone = pn;
                phoneLen = len;
                sms = message;
                if (message.Length > 140)
                {
                    command += string.Format("{0:D}", 154) + "\r\n";
                    data += len + "91" + pn + "0004AA";

                    string dtlen = string.Format("{0:X2}", 140);
                    data += dtlen;
                    for (int i = 0; i < 140; i++)
                        data += string.Format("{0:X2}", Convert.ToByte(message[i]));
                    receiveFlag = WMA_FLAG_OVER140BYTESMES;
                    sp.Write(command);
                    sp.Write(data + (char)26);
                }
                else
                {
                    command += string.Format("{0:D}", 14 + message.Length) + "\r\n";
                    data += len + "91" + pn + "0004AA";

                    string dtlen = string.Format("{0:X2}", message.Length);
                    data += dtlen;
                    for (int i = 0; i < message.Length; i++)
                        data += string.Format("{0:X2}", Convert.ToByte(message[i]));
                    sp.Write(command);
                    sp.Write(data + (char)26);
                }
            }
            else if (mode == 1)
            {
                sp.Write("AT+CMGF=1\r\n");
                command = "AT+CMGS=\"" + pn + "\"" + "\r\n";
                data = message;
                sp.Write(command);
                sp.Write(data + (char)26);
            }
            return "OK";
        }

        private void SendSecondMessage()
        {
            string command = "AT+CMGS=";
            string data = "001100";

            command += string.Format("{0:D}", 14 + sms.Length - 140) + "\r\n";
            data += phoneLen + "91" + phone + "0004AA";

            string dtlen = string.Format("{0:X2}", sms.Length - 140);
            data += dtlen;
            for (int i = 140; i < sms.Length; i++)
                data += string.Format("{0:X2}", Convert.ToByte(sms[i]));
            receiveFlag = WMA_FLAG_NORMALSTATE;
            sp.Write(command);
            sp.Write(data + (char)26);
        }

        internal class ProcessConnection
        {

            public static ConnectionOptions ProcessConnectionOptions()
            {
                ConnectionOptions options = new ConnectionOptions();
                options.Impersonation = ImpersonationLevel.Impersonate;
                options.Authentication = AuthenticationLevel.Default;
                options.EnablePrivileges = true;
                return options;
            }

            public static ManagementScope ConnectionScope(string machineName, ConnectionOptions options, string path)
            {
                ManagementScope connectScope = new ManagementScope();
                connectScope.Path = new ManagementPath(@"\\" + machineName + path);
                connectScope.Options = options;
                connectScope.Connect();
                return connectScope;
            }
        }

        public class COMPortInfo
        {
            public string Name { get; set; }
            public string Description { get; set; }

            public COMPortInfo() { }

            public static List<COMPortInfo> GetCOMPortsInfo()
            {
                List<COMPortInfo> comPortInfoList = new List<COMPortInfo>();

                ConnectionOptions options = ProcessConnection.ProcessConnectionOptions();
                ManagementScope connectionScope = ProcessConnection.ConnectionScope(Environment.MachineName, options, @"\root\CIMV2");

                ObjectQuery objectQuery = new ObjectQuery("SELECT * FROM Win32_PnPEntity WHERE ConfigManagerErrorCode = 0");
                ManagementObjectSearcher comPortSearcher = new ManagementObjectSearcher(connectionScope, objectQuery);

                using (comPortSearcher)
                {
                    string caption = null;
                    foreach (ManagementObject obj in comPortSearcher.Get())
                    {
                        if (obj != null)
                        {
                            object captionObj = obj["Caption"];
                            if (captionObj != null)
                            {
                                caption = captionObj.ToString();
                                if (caption.Contains("(COM"))
                                {
                                    COMPortInfo comPortInfo = new COMPortInfo();
                                    comPortInfo.Name = caption.Substring(caption.LastIndexOf("(COM")).Replace("(", string.Empty).Replace(")",
                                                                         string.Empty);
                                    comPortInfo.Description = caption;
                                    comPortInfoList.Add(comPortInfo);
                                }
                            }
                        }
                    }
                }
                return comPortInfoList;
            }
        }
    }
}